import 'dart:async';
import 'dart:convert';

import 'package:build/build.dart';

class LocalizationInterfaceBuilder implements Builder {
  @override
  final buildExtensions = const {
    'lib/lang/zh.json': ['lib/lang/my_localizations.dart'], // 👈 这里必须声明它会生成文件
    // '.json': [],这样会导致 不会生成任何文件，因为扩展映射为空数组，build_runner 不知道输出目标。
    //使用文件的相对路径
  };

  @override
  Future<void> build(BuildStep buildStep) async {
    final inputId = buildStep.inputId;
    final langCode = inputId.pathSegments.last.split('.').first;

    // 只在 zh.json 生成 my_localizations.dart
    if (langCode != 'zh') return;

    final content = await buildStep.readAsString(inputId);
    final map = json.decode(content) as Map<String, dynamic>;

    final interfaceBuffer = StringBuffer();
    interfaceBuffer.writeln('// GENERATED CODE - DO NOT MODIFY BY HAND');
    interfaceBuffer.writeln('abstract class MyLocalizations {');
    for (final key in map.keys) {
      interfaceBuffer.writeln('  String get $key;');
    }
    interfaceBuffer.writeln('}');
    //使用文件的相对路径
    final outputId = AssetId(inputId.package, 'lib/lang/my_localizations.dart');
    await buildStep.writeAsString(outputId, interfaceBuffer.toString());
  }
}

Builder localizationInterfaceBuilder(BuilderOptions options) => LocalizationInterfaceBuilder();
